package es.decoroso.communicationAgent;

import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import es.decoroso.communicationAgent.bean.Message;
import es.decoroso.communicationAgent.behaviours.ProcessMessage;
import es.decoroso.communicationAgent.comunicationServer.CommunicationServer;

/**
 * This agents creates a server that sends all the information to the
 * graphic layer
 * 
 * @author Jesús W. Jiménez
 */
public class CommunicationAgent extends Agent {
	
	/** Port used to comunicate with server */
	private static int PORT = 9000;
	/** Comunication Server */
	private CommunicationServer server;

	/**
	 * Register as COMMUNICATION, start the server and add behaviours
	 */
	@Override
	protected void setup() {
		super.setup();
		System.out.println("Starting Communication Server");
		registerComunication();
		
		
		// Start the communication server
		server = new CommunicationServer(PORT, this);
		new Thread(server).start();
		
		// Add behaviours
		addBehaviour(new ProcessMessage(this));
	}

	private void registerComunication() {
		try {
			registrarAgente(this,"COMMUNICATION");
			
		} catch (FIPAException ex) {
			doDelete();
			return;
		}
	}
	
	private void registrarAgente(Agent agente, String tipo) throws FIPAException {

		DFAgentDescription dfd = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setName(agente.getName());
		sd.setType(tipo);
		dfd.addServices(sd);

		DFService.register(agente, dfd);
	}

	public void treatMessage(Message ms) {
		//System.out.println("CommunicationAgent: Received ms: \n" + ms.toJSON().toString());
		server.setMessage(ms);
	}
}
